<template>
  <div class="app-container">


    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="100px">
      <el-form-item label="clientId" prop="deviceClientId">
        <el-input
          v-model="queryParams.deviceClientId"
          placeholder="请输入clientId"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最后连接时间">
        <el-date-picker
          v-model="daterangeLastConnectionTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="最后离线时间">
        <el-date-picker
          v-model="daterangeLastDisconnectionTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="设备组" prop="groupId">
        <el-select v-model="queryParams.groupId" filterable placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.groupId"
            :label="'设备组id:'+item.groupId +' 设备组名:' +item.groupName"
            :value="item.groupId">
          </el-option>
        </el-select>

        <!--              <el-input-->
        <!--                v-model="queryParams.groupId"-->
        <!--                placeholder="请输入设备组id"-->
        <!--                clearable-->
        <!--                @keyup.enter.native="handleQuery"-->
        <!--              />-->
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:devices:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['iot:devices:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:devices:delete']"
        >删除
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:devices:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-promotion"
          size="mini"
          :disabled="multiple"
          @click="handleSendMsg"
          v-hasPermi="['iot:devices:send']"
        >消息推送
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="devicesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="clientId" align="center" prop="deviceClientId"/>
      <el-table-column label="设备名" align="center" prop="deviceName"/>
      <el-table-column property="connected" label="连接状态">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.connected">已连接</el-tag>
          <el-tag type="info" v-else>离线</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="最后连接时间" align="center" prop="lastConnectionTime" width="180">

      </el-table-column>

      <el-table-column label="离线时间" align="center" prop="lastDisconnectionTime" width="180">

      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="设备组id" align="center" prop="groupId"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:devices:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:devices:delete']"
          >删除
          </el-button>


          <el-tooltip class="item" effect="dark" content="重置设备，更改设备名后设备并未退出占用了clientId" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh"
              v-has-permi="['iot:devices:reset']"
              @click="handlReset(scope.row)"
            >重置在线状态
            </el-button>
          </el-tooltip>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleSendMsg(scope.row)"
            v-hasPermi="['iot:devices:send']"
          >推送消息
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改devices对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="clientId" prop="deviceClientId">
          <el-input v-model="form.deviceClientId" placeholder="请输入clientId"/>
        </el-form-item>
        <el-form-item label="设备名" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="设备组id" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.groupId"
              :label="'设备组id:'+item.groupId +' 设备组名:' +item.groupName"
              :value="item.groupId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="消息推送"  :visible.sync="dialogFormVisible">
      <el-form ref="mqttMsg" width="500px" :model="mqttMsg" :rules="mqttMsgRules">
        <el-form-item label="消息内容" prop="content" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="mqttMsg.content"></el-input>
        </el-form-item>
        <el-form-item label="是否保留消息" :label-width="formLabelWidth" prop="retained">
          <el-select  style="width: 100%" v-model="mqttMsg.retained" placeholder="请选择是否为保留消息">
            <el-option label="保留消息（设备即使不在线，上线后也会接收到此消息，但是保留消息只能有一条）" :value="true"></el-option>
            <el-option label="普通消息（设备不在线时推送是无效的）" :value="false"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="mqttMsgCancel">取 消</el-button>
        <el-button type="primary" @click="submitMsgForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listDevices, getDevices, delDevices, addDevices, updateDevices, reset, sendMsg} from "@/api/iot/devices";
import {listGroup} from "@/api/iot/group";
import {EventBus} from '@/utils/EventBus';

export default {
  name: "Devices",
  components: {},
  dicts: ['sys_normal_disable'],
  data() {
    return {

      options: [],
      optionsParams: {
        pageNum: 1,
        pageSize: 10000,
        iCreated: null,
        groupName: null,
        secretKey: null,
        secretValue: null,
        adminUserId: null,
        status: null
      },
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // devices表格数据
      devicesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态时间范围
      daterangeLastConnectionTime: [],
      daterangeLastDisconnectionTime: [],
      dialogFormVisible: false,
      formLabelWidth: '120px',
      mqttMsg: {
        deviceIds:null,
        content: null,
        retained: false,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceClientId: null,
        deviceName: null,
        lastConnectionTime: null,
        lastDisconnectionTime: null,
        groupId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceClientId: [
          {required: true, message: "clientId不能为空", trigger: "blur"},
          {
            pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
            message: '设备组名格式不正确，必须以字母开头，允许输入字母、数字和下划线',
            trigger: 'blur'
          }

        ],
        deviceName: [
          {required: true, message: "设备名不能为空", trigger: "blur"},
          {
            pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
            message: '设备组名格式不正确，必须以字母开头，允许输入字母、数字和下划线',
            trigger: 'blur'
          }

        ],
        groupId: [
          {required: true, message: "设备组id不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "状态不能为空", trigger: "change"}
        ]
      },
      mqttMsgRules: {
        content: [
          {required: true, message: "消息内容不能为空", trigger: "blur"},
        ],
        retained: [
          {required: true, message: "是否保留消息不能为空", trigger: "blur"},
        ]
      }
    };
  },
  created() {
    this.getMyGroup();
    this.getList();
    EventBus.$on('GroupAdded', this.getMyGroup);

  },
  beforeDestroy() {
    EventBus.$off('GroupAdded', this.getMyGroup);

  },
  methods: {
    getMyGroup() {
      this.loading = true;

      listGroup(this.optionsParams).then(response => {
        this.options = response.rows;
        console.log(this.options)
        this.loading = false;
      });
    },
    /** 查询devices列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeLastConnectionTime && '' != this.daterangeLastConnectionTime) {
        this.queryParams.params["beginLastConnectionTime"] = this.daterangeLastConnectionTime[0];
        this.queryParams.params["endLastConnectionTime"] = this.daterangeLastConnectionTime[1];
      }
      if (null != this.daterangeLastDisconnectionTime && '' != this.daterangeLastDisconnectionTime) {
        this.queryParams.params["beginLastDisconnectionTime"] = this.daterangeLastDisconnectionTime[0];
        this.queryParams.params["endLastDisconnectionTime"] = this.daterangeLastDisconnectionTime[1];
      }

      listDevices(this.queryParams).then(response => {
        this.devicesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        deviceClientId: null,
        deviceName: null,
        lastConnectionTime: null,
        lastDisconnectionTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        groupId: null,
        status: '0'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeLastConnectionTime = [];
      this.daterangeLastDisconnectionTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加devices";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids
      getDevices(deviceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改devices";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            updateDevices(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevices(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal.confirm('是否确认删除devices编号为"' + deviceIds + '"的数据项？').then(function () {
        return delDevices(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    handlReset(row) {
      reset(row.deviceClientId).then(() => {
        this.$modal.msgSuccess("重置成功");

      }).catch(() => {

      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/devices/export', {
        ...this.queryParams
      }, `devices_${new Date().getTime()}.xlsx`)
    },

    handleSendMsg(row) {
      this.dialogFormVisible = true;
      this.mqttMsg.deviceIds = row.deviceId || this.ids;
      //sendMsg(deviceIds, {topic: "topic", content: "content"})
    },

    submitMsgForm() {
      this.$refs["mqttMsg"].validate(valid => {
        if (valid && this.mqttMsg.deviceIds!=null) {
          sendMsg(this.mqttMsg.deviceIds, this.mqttMsg).then(res=>{
            this.$modal.msgSuccess("消息推送成功");
          }).finally(()=>{
            this.mqttMsgCancel()
          })
        }

      });
    },
    mqttMsgCancel(){
      this.dialogFormVisible = false;
      this.mqttMsg.retained = false;
      this.mqttMsg.content=null;
      this.mqttMsg.deviceIds = null;
    }
  }
};
</script>
